#!/usr/bin/env python
# -*- coding:utf-8 -*-

from rest_framework import serializers
from .models import User
import re
from django_redis import get_redis_connection

"""注册使用的序列化器"""


class RegisterUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label="确认密码", write_only=True, allow_blank=False, allow_null=False)

    sms_code = serializers.CharField(label="短信验证码", write_only=True, allow_blank=False, allow_null=False)

    allow = serializers.CharField(label="是否同意协议", write_only=True, allow_blank=False, allow_null=False)

    token = serializers.CharField(label="token", read_only=True)

    class Meta:
        model = User
        fields = ["username", "password", "mobile", "password2", "sms_code", "allow", "token"]
        # 设置自动生成字段的选项
        extra_kwargs = {
            "username": {
                "min_length": 5,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许５－２０个字符的用户名",
                    "max_length": "仅允许５－２０个字符的用户名",
                }
            },
            "password": {
                "write_only": True,
                "min_length": 8,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许８－２０个字符的密码",
                    "max_length": "仅允许８－２０个字符的密码",
                }
            }
        }

    # 校验手机号
    def validate_mobile(self, value):

        if not re.match("1[3-9]\d{9}", value):
            raise serializers.ValidationError("手机号不符合规范")

        return value

    # 校验是否同意协议
    def validate_allow(self, value):
        if value != "true":
            raise serializers.ValidationError("没有同意用户协议")
        return value

    # 对确认密码进行校验及短信验证码的校验
    def validate(self, attrs):
        password = attrs.get("password")
        password2 = attrs.get("password2")
        if password != password2:
            raise serializers.ValidationError("两次输入的密码不一致")

        # 校验短信验证码,
        # 先获取前端验证码
        sms_code = attrs.get("sms_code")
        mobile = attrs.get("mobile")
        # 再获取redis中的验证码
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get("sms_%s" % mobile)

        if redis_sms_code is None:
            raise serializers.ValidationError("短信验证码已过期")
        # 对比
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError("短信验证码输入有误")

        return attrs

    def create(self, validated_data):
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        user = super().create(validated_data)

        user.set_password(validated_data["password"])
        user.save()

        # {"username":"zhangwei","mobile":"18999999999"}前端需要把这两个字段生成ｔｏｋｅｎ信息
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER

        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)

        token = jwt_encode_handler(payload)

        user.token = token
        return user


# {"username":"dazuo","mobile":"15999999999","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo2LCJlbWFpbCI6IiIsImV4cCI6MTUzOTY4NjEzOCwidXNlcm5hbWUiOiJkYXp1byJ9.vQr7okUk3zCWJlB_08H1Si7OHfcRtXnVXJju6mOxN50"}

from rest_framework import serializers

"""用户中心的序列化器"""


class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


"""邮件的序列化器"""
from rest_framework import serializers
from django.conf import settings


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'email']

        extra_kwargs = {
            "email": {
                "required": True
            }
        }

    def update(self, instance, validated_data):
        # 更新数据
        email = validated_data.get("email")
        instance.email = email
        instance.save()

        ##############发送激活邮件################
        # from django.core.mail import send_mail
        # # subject, message, from_email, recipient_list,必须传递的参数
        # subject = "美多商城激活邮件"
        # message = ""
        # from_email = settings.EMAIL_FROM  # 发件人
        # recipient_list = [email]  # 收件人列表
        # # 生成激活链接
        # # html_message = "<h1>做做做</h1>"
        #
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。' \
        #                '请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, url, url)
        #
        # send_mail(subject, message, from_email, recipient_list, html_message=html_message)

        url = instance.generic_verify_url()
        from celery_tasks.email.tasks import send_active_email
        send_active_email.delay(email,url)

        return instance


# class UserListSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = User
#         fields = ["id", "username", "mobile"]

from .models import Address

class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


from goods.models import SKU
from rest_framework import serializers
from django_redis import get_redis_connection

class UserBrowsingHistorySerializer(serializers.Serializer):
    """用户历史浏览记录"""
    sku_id = serializers.CharField(label="商品id", required=True)

    # 校验sku_id是否存在
    def validate_sku_id(self, value):
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError("商品不存在")

        return value

    def create(self, validated_data):
        # 获取sku_id
        sku_id = validated_data.get("sku_id")

        redis_conn = get_redis_connection('history')
        # 列表有一个key ，这个key 肯定要区分不同的用户
        user = self.context.get("request").user
        # 先将保存的数据删除，进行浏览记录去重
        redis_conn.lrem('history_%s'%user.id,0,sku_id)
        # 再将商品信息存储到用户的浏览历史列表中
        redis_conn.lpush('history_%s'%user.id,sku_id)
        # 只保留５条记录
        # 对一个列表进行修剪(trim),就是说，让列表只保留指定区间的元素
        # 不在指定区间之内的元素都将被删除
        redis_conn.ltrim('history_%s'%user.id,0,4)


        return validated_data


class SKUSerialzier(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')
